﻿Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Net.Sockets
Imports System.IO
Imports System.Net.Security
Imports System.Net

Public Class SSLPlugin
    Implements IMailNotifyPlugin

    Private _Exception As Exception
    Private _NewMessageCount As Integer
    Private _AccountName As String = String.Empty
    Private _Settings As AccountSettings

    Private _Worker As New BackgroundWorker

    Public ReadOnly Property AccountName() As String Implements IMailNotifyPlugin.AccountName
        Get
            Return Me._AccountName
        End Get
    End Property

    Public Sub CheckMail(ByVal AccountName As String) Implements IMailNotifyPlugin.CheckMail
        If NetworkInformation.NetworkInterface.GetIsNetworkAvailable() Then
            Dim config As New Configbase(Of AccountSettings)(AccountName)
            Me._Settings = config.ReadSettings
            Me.CheckPOP3Inbox()
        End If
    End Sub

    Public ReadOnly Property Exception() As System.Exception Implements IMailNotifyPlugin.Exception
        Get
            Return Me._Exception
        End Get
    End Property
    Private Sub ShowStatus(ByVal Status As String)
        RaiseEvent StatusChanged(Status)
    End Sub
    Private Sub CheckPOP3Inbox()
        Dim oTcpClient As New TcpClient
        Dim oNetworkStream As SslStream
        Dim oMessage As String
        Dim oResult As Boolean
        Try
            With oTcpClient
                .Connect(Me._Settings.ServerIp, Integer.Parse(Me._Settings.ServerPort))
                oNetworkStream = New SslStream(.GetStream)
                oNetworkStream.AuthenticateAsClient(Me._Settings.ServerIp)
                Dim sw As New StreamWriter(oNetworkStream)
                Dim sr As New StreamReader(oNetworkStream)

                oResult = CheckError(sr.ReadLine())
                If Not oResult Then
                    sw.WriteLine(String.Format("USER {0}", Me._Settings.Username))
                    sw.Flush()
                End If
                oResult = CheckError(sr.ReadLine())
                If Not oResult Then
                    sw.WriteLine(String.Format("PASS {0}", Me._Settings.Password))
                    sw.Flush()
                End If
                oResult = CheckError(sr.ReadLine())
                If Not oResult Then
                    sw.WriteLine("STAT ")
                    sw.Flush()
                End If
                oMessage = sr.ReadLine
                Dim MsgCount As String = oMessage.Split(New String() {" "}, _
                                                        StringSplitOptions.RemoveEmptyEntries)(1)
                Me._NewMessageCount = Integer.Parse(MsgCount)
                sw.WriteLine("Quit ")
                sw.Flush()
                sw.Close()
                sr.Close()
                oNetworkStream.Close()
                oTcpClient.Close()
            End With
        Catch ex As Exception
            Me.ErrorHandler(ex)
        End Try
    End Sub
    Public ReadOnly Property NewMailCount() As Integer Implements IMailNotifyPlugin.NewMailCount
        Get
            Return Me._NewMessageCount
        End Get
    End Property
    Public Sub Initialize(ByVal context As System.Collections.Generic.Dictionary(Of String, Object)) Implements IMailNotifyPlugin.Initialize

    End Sub

    Private Sub ErrorHandler(ByVal ex As Exception)
        Me._Exception = ex
    End Sub
    Private Function CheckError(ByVal Status As String) As Boolean
        Dim oResult As Boolean = False
        Try
            If Status.IndexOf("+OK") >= -1 AndAlso Status.IndexOf("-ERR") >= 0 Then
                Me.ErrorHandler(New Exception(Status.Split(New Char() {" "})(1)))
                oResult = True
            End If
        Catch ex As Exception
            'do nothing
            Me.ErrorHandler(ex)
        End Try
        Return oResult
    End Function

    Public Event StatusChanged(ByVal Status As String) Implements IMailNotifyPlugin.StatusChanged

    Public ReadOnly Property EmailAddress() As String Implements IMailNotifyPlugin.EmailAddress
        Get
            Throw New NotImplementedException
        End Get
    End Property
End Class
